﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using BLL;
using DAL;
using DataProj.Areas.BackSys.ServiceTools;
using Model;
using System.Text.Json;
using static Newtonsoft.Json.JsonConvert;
using System.Text.Json.Serialization;
using MQTools;
using Newtonsoft.Json;

namespace DataProj.Areas.BackSys.Controllers
{
    public class ComplaintController : BaseController
    {
        // GET: Complaint
        // GET: /BackSys/Complaint/
        private static ComplaintBagImpl _impl;

        public ComplaintController()
        {
            if (_impl == null) _impl = new ComplaintBagImpl();

            if (string.IsNullOrEmpty(MySession.GetSession("complaintRows")))
            {
                MySession.WriteSession("complaintRows", 10);
            }
            if (string.IsNullOrEmpty(MySession.GetSession("complaintPage")))
            {
                MySession.WriteSession("complaintPage", 1);
            }
        }



        [HttpPost]
        public ActionResult ChangePage()
        {
            int page = Convert.ToInt16(Request["pageNum"].Trim());
            MySession.WriteSession("complaintPage", page);
            int rows = Convert.ToInt16(MySession.GetSession("complaintRows"));
            IDictionary<string,string>set = new Dictionary<string,string>();
            
            switch (LoginType)
            {
                case "用户":
                    UserInfo detail = MySession.GetSession_UserInfo("detail");
                    (var userTotalPages,var  userComplaints) = _impl.GetList(detail.UserName.Trim(), detail.Phone.Trim(), rows, page);

                    MySession.WriteSession("complaintTotalPages", userTotalPages);
                    set.Add("totalPages", userTotalPages.ToString());
                    set.Add("data", JsonConvert.SerializeObject(userComplaints));
                    return Json(JsonConvert.SerializeObject(set));
                case "管理员":
                case "快递员":
                    (var totalPages,var complaints) = _impl.GetList(rows, page);
                    set.Add("totalPages", totalPages.ToString());
                    set.Add("data", JsonConvert.SerializeObject(complaints));
                    MySession.WriteSession("complaintTotalPages", totalPages);
                    //ViewBag.Complaints = data;
                    return Json(JsonConvert.SerializeObject(set));
              
                default:
                    break;
            }

            return Json(0);
        }

        public ActionResult ComplaintManage()
        {
           // int page = 0, rows = 10,totalPages=0;
           // IList<ComplaintBag> data = null;
            
     
           //page = Convert.ToInt16(MySession.GetSession("complaintPage"));
           //rows = Convert.ToInt16(MySession.GetSession("complaintRows"));
       
           // switch (LoginType)
           // {
           //     case "用户":
           //         UserInfo detail = MySession.GetSession_UserInfo("detail");
           //         (totalPages, data) = _impl.GetList(detail.UserName.Trim(), detail.Phone.Trim(), rows, page);
           //         MySession.WriteSession("complaintTotalPages", totalPages);
           //         ViewBag.ComplaintBags = data;
           //         return PartialView();
           //     case "管理员":
           //     case "快递员":
           //         (totalPages, data) = _impl.GetList(rows, page);
           //         MySession.WriteSession("complaintTotalPages", totalPages);
           //         ViewBag.ComplaintBags = data;
           //         return PartialView();
           //     default:
           //         break;
           // }


            //return PartialView(_impl.GetList());
            return PartialView();

        }
        public ActionResult List()
        {
            int page = 1;
            if (!string.IsNullOrWhiteSpace(Request["complaintPage"]))
            {
                if (int.TryParse(Request["complaintPage"], out page))
                {
                    if (page < 1)
                    {
                        page = 1;
                    }
                };
            }
            int rows = 10;
            if (!string.IsNullOrWhiteSpace(Request["complaintRows"]))
            {
                if (int.TryParse(Request["complaintRows"], out rows))
                {
                    if (rows < 10)
                    {
                        rows = 10;
                    }
                    else if (rows > 30)
                    {
                        rows = 30;
                    }
                }
            }
            
            return Json(new
            {
                rows = _impl.GetList(rows,page),
                total = _impl.ExistNum
            },
                JsonRequestBehavior.AllowGet);
        }


        //
        // GET: /BackSys/Complaint/Details/5
        [HttpPost]
        public ActionResult GetItemByID(int id,string action)
        {
            var tool = new JavaScriptSerializer();
            Complaint result = _impl.Find(id); 
            if (result != null)
            {
                string seri = tool.Serialize(result);              
                return Json(seri);
            }
            return Json(null);
        }

        //
        // GET: /BackSys/Complaint/Create

        public ActionResult Create()
        {
            return PartialView();
        }

        //
        // POST: /BackSys/Complaint/Create

        [HttpPost]
        public ActionResult Add()
        {
            Complaint complaint = new Complaint();

            //complaint.ID = Convert.ToInt32(Request["ID"].Trim());
            var action = Request["Action"];
            complaint.TrueName = Request["TrueName"].Trim();
     
            complaint.Title = Request["Title"].Trim();
            complaint.Info = Request["Info"].Trim();
            complaint.BagID = Request["BagID"].Trim();
            Bag bag = new BagInfoImpl().Find(complaint.BagID);
            complaint.Phone = Request["Phone"].Trim();
            complaint.IDCard = Request["IDCard"].Trim();
            complaint.SubmitTime = DateTime.Now;
            complaint.ReplyTime = null;
            if (_impl.Add(complaint))
            {
                MqSender.SendMessage(new QueueMessage()
                {
                    Action = QueueMessage.ActionType.COMPLAINT_SUBMIT,
                    Complaint = complaint,
                    User = new UserInfo() { ID = Convert.ToInt16(MySession.GetSession("userID"))}
                }, Resources.CompanyComplaintRoute);
                return Json(1);
            }
            return Json(0);
        }

        [HttpPost]
        public ActionResult GetBagIDs()
        {
            UserInfo detail = MySession.GetSession_UserInfo("detail") as UserInfo;
            var ids = new BagInfoImpl().GetList(detail.UserName, detail.Phone);
            if (ids == null) return Json(JsonConvert.SerializeObject(new List<string>()));
            return Json(JsonConvert.SerializeObject(ids[0].Concat(ids[1]).Select(o => o.BagID).ToArray()));
        }
        public ActionResult ComplaintSubmit()
        {

                switch (LoginType)
                {
                    case "用户":
                        return PartialView();
                    case "管理员":
                    case "快递员":
                        return RedirectToAction("Index","Home");
                    default:
                        break;
                }
         

            return PartialView(new BagInfoImpl().GetList());
        }


        [HttpPost]
        public ActionResult Update()
        {
            int id = Convert.ToInt32(Request["ID"]);
            string bagID = (Request["BagID"]).Trim();
            Complaint complaint = new Complaint();
            if (LoginType.Equals("用户"))
            {
                complaint.Info = Request["Info"];
                if (_impl.Update(id, complaint))
                {
                    MqSender.SendMessage(new QueueMessage()
                    {
                        Action = QueueMessage.ActionType.COMPLAINT_UPDATE,
                        Complaint = complaint,
                        User = new UserInfo() { ID = Convert.ToInt16("userID") }
                    }, Resources.CompanyComplaintRoute);
                    return Json(1);
                }
               
            }
            else
            {
                complaint.ReplyInfo = Request["ReplyInfo"];
                complaint.ReplyTime = DateTime.Now;
                if (_impl.Update(id, complaint))
                {
                    MqSender.SendMessage(new QueueMessage()
                    {
                        Action = QueueMessage.ActionType.COMPLAINT_REPLY,
                        Complaint = complaint,
                        User = new UserInfo() { ID=_impl.GetSenderUserIDByBagID(bagID)}
                    }, Resources.CustomerComplaintRoute);
                    return Json(1);
                }
               
            }
            //complaint.BagID = Request["BagID"];
            //complaint.TrueName = Request["TrueName"];
            //complaint.Phone = Request["Phone"];
            //complaint.IDCard = Request["IDCard"];
            //complaint.Title = Request["Title"];
            //complaint.Info = Request["Info"];
            //complaint.SubmitTime = DateTime.Now;
            //complaint.AddTime = DateTime.Now;

            return Json(0);

        }

        //
        // GET: /BackSys/Complaint/Delete/5
        [HttpPost]
        public ActionResult Delete(int id = 0)
        {

            if (_impl.Delete(id))
            {
                if (LoginType.Equals("用户")) MqSender.SendMessage(
                    new QueueMessage()
                    {
                        Action = QueueMessage.ActionType.COMPLAINT_DELETE,
                        Complaint = new Complaint() { ID = id },
                        User= new UserInfo() { ID = Convert.ToInt16(MySession.GetSession("userID"))}
                    },
                    Resources.CompanyComplaintRoute);
                else
                {
                    MqSender.SendMessage(
                     new QueueMessage()
                     {
                         Action = QueueMessage.ActionType.COMPLAINT_DELETE,
                         Complaint = new Complaint() { ID = id },
                         User = new UserInfo() { ID = _impl.GetSenderUserIDByComplaintID(id) }
                     },
                     Resources.CustomerComplaintRoute);
                    MqSender.SendMessage(
                     new QueueMessage()
                     {
                         Action = QueueMessage.ActionType.COMPLAINT_DELETE,
                         Complaint = new Complaint() { ID = id },
                         User = new UserInfo() { ID = _impl.GetGetterUserIDByComplaintID(id) }
                     },
                     Resources.CustomerComplaintRoute);
                } 
                    
                 
                return Json(1);
            }


            return Json(0);
        }

        //
        // POST: /BackSys/Complaint/Delete/5
        protected override void Dispose(bool disposing)
        {
            _impl.Dispose();
            base.Dispose(disposing);
        }
    }
}